﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Entity;

namespace UDS.Web.UI.Controls
{
    public class CatalogDropDownList : DropDownList
    {
        /// <summary>
        /// Indicates whether to display the "ALL" item.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        [DefaultValue("(*)")]
        public bool IgnoreItemAll
        {
            get;
            set;
        }

        /// <summary>
        /// Get or set the selected catalog.
        /// </summary>
        public int SelectedCatalog
        {
            get
            {
                int catalogId;
                if (int.TryParse(SelectedValue, out catalogId))
                {
                    return catalogId;
                }
                return -1;
            }
            set
            {
                ClearSelection();
                ListItem listItem = Items.FindByValue(value.ToString());
                if (listItem != null)
                {
                    listItem.Selected = true;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            Items.Clear();
            if (!IgnoreItemAll)
            {
                Items.Add(new ListItem("== 全部 ==", "-1"));
            }

            foreach (var catalog in CommonFile.GetCatalogs())
            {
                var listItem = new ListItem(catalog.Catalog, catalog.CatalogID.ToString());
                Items.Add(listItem);
            }

            base.OnInit(e);
        }
    }
}
